package rifl.meres4.commons.ui;

import javax.swing.SwingUtilities;

import org.osgi.service.log.LogService;

import rifl.meres4.commons.StepWorker;
import rifl.meres4.commons.step.IWorkflowStep;

public abstract class AbstractGUI implements Runnable {

	// log
	protected LogService log;
	private boolean started = false;
	
	@Override
	public void run() {
		initializeGUI();
	}
	
	abstract protected void initializeGUI();
	abstract protected void disposeGUI();
	
	public void start() {
		if (started) return;
		run();
		started = true;
	}
	
	public void stop() {
		if (!started) return;
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				disposeGUI();
				started = false;
			}
		});
	}
	
	public LogService getLog() {
		return log;
	}

	public void setLog(LogService log) {
		this.log = log;
	}
	
	public void unsetLog(LogService log) {
		if (this.log == log) {
			this.log = null;
		}
	}
	
	protected void callStep(StepFrame stepFrame,
			IWorkflowStep workflowStep) {
		if (workflowStep == null) {
			if (log != null) {
				log.log(LogService.LOG_ERROR, "Service currently unavailable!");
			} else {
				System.err.println("LogService currently unavailable! Workflow Service also unavailable!");
			}
		} else {
			if (log != null) {
				log.log(LogService.LOG_INFO, "Calling "+workflowStep.getClass().getName()+" from StepWorker!");						
			} else {
				System.out.println("Calling "+workflowStep.getClass().getName()+" from StepWorker!");
			}
			preCallStep(stepFrame, workflowStep);
			new StepWorker(stepFrame, workflowStep).execute();
		}
	}

	protected void preCallStep(StepFrame stepFrame, IWorkflowStep workflowStep) {
	}
	
	protected void unregister(IWorkflowStep step,
			StepFrame frame) {
		if (step == null) return;
		if (this.log != null) {
			this.log.log(LogService.LOG_INFO, step.getClass().getName() + " Service unavailable!");
		}
		step.unregisterMessageListener(frame);
		frame.getNextButton().setEnabled(false);
		String prevText = frame.getTextArea().getText();
		frame.getTextArea().setText(prevText + "\n-----\nService Unavailable!\n-----\n");		
	}
	
	protected void register(IWorkflowStep step, StepFrame frame) {
		if (step == null) return;
		if (this.log != null) {
			this.log.log(LogService.LOG_INFO, step.getClass().getName() + " Service available!");
		}
		step.registerMessageListener(frame);
		String prevText = frame.getTextArea().getText();
		frame.getTextArea().setText(prevText + "\n-----\nService available!\n-----\n");
	}

}
